package itsm.isperp.module.controller.sparepart;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.PageResponse;
import itsm.isperp.framework.domain.IUser;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.web.controller.BaseController;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.entity.project.ProjProject;
import itsm.isperp.module.entity.sparepart.SptSparepartPlan;
import itsm.isperp.module.entity.sparepart.SptSparepartRelation;
import itsm.isperp.module.service.app.AppDictService;
import itsm.isperp.module.service.configuration.ConfCiService;
import itsm.isperp.module.service.customer.CusCustomerService;
import itsm.isperp.module.service.project.ProjProjectService;
import itsm.isperp.module.service.provider.PrdProviderService;
import itsm.isperp.module.service.sparepart.SptSparepartCategoryService;
import itsm.isperp.module.service.sparepart.SptSparepartChangeDetailService;
import itsm.isperp.module.service.sparepart.SptSparepartInDetailService;
import itsm.isperp.module.service.sparepart.SptSparepartPlanService;
import itsm.isperp.module.service.sparepart.SptSparepartRelationService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * 备件管理控制器
 * 
 * @author lizx
 * @date 2013-9-12
 */
@Controller
@RequestMapping("sparepart/sparepart/plan")
public class SptSparepartPlanController extends
    BaseController<SptSparepartPlan> {

  @Autowired
  protected SptSparepartPlanService sptSparepartPlanService;

  @Autowired
  protected SptSparepartCategoryService sptSparepartCategoryService;

  @Autowired
  protected SptSparepartInDetailService sptSparepartInDetailService;

  @Autowired
  protected SptSparepartChangeDetailService sptSparepartChangeDetailService;

  @Autowired
  protected ProjProjectService projProjectService;

  @Autowired
  protected PrdProviderService prdProviderService;

  @Override
  public SptSparepartPlanService getService() {
    return sptSparepartPlanService;
  }

  @Override
  public String getPageTitle() {
    return "备件管理";
  }

  @RequestMapping("listDetail")
  @ResponseBody
  public PageResponse<Map<String, Object>> listDetail(JqGridRequest request,
      HttpServletRequest req) {

    String type = req.getParameter("sptType");
    String relationId = req.getParameter("relationId");
    if (StringUtils.isNotEmpty(type) && StringUtils.isNotEmpty(relationId)) {
      List<Map<String, Object>> list = null;
      if (type.equalsIgnoreCase("in")) // 入库
      {
        list = this.sptSparepartInDetailService
            .findAllDetailBySparepartInId(relationId);
      } else // 出库
      {
        list = this.sptSparepartChangeDetailService
            .findAllDetailByRelationId(relationId);
      }
      String selectedSpt = "";
      for (Map<String, Object> map : list) {
        selectedSpt = selectedSpt + "'"
            + map.get("spt_sparepart_id").toString() + "',";
      }
      if (selectedSpt.length() > 0) {
        selectedSpt = selectedSpt.substring(0, selectedSpt.length() - 1);
        request.addFilterRule("id", JqGridFilterRuleOp.ni, selectedSpt);
      }

    }

    request.addFilterRule("use_status", JqGridFilterRuleOp.eq, "1");
    return this.getService().findAllDetailByRequest(request);

  }

  @RequestMapping("listSparepartAllList")
  @ResponseBody
  public PageResponse<Map<String, Object>> listSparepartAllList(
      JqGridRequest request, HttpServletRequest req) {

    return this.getService().findSparepartAllList(request);

  }

  @RequestMapping(value = { "sptAllProcessManage", "" })
  public ModelAndView sptAllProcessManage(HttpServletRequest req) {
    ModelAndView mv = this.getModelAndView();
    ProjProjectService projProjectService = ContextHolder
        .getSpringBean("projProjectService");
    mv.addObject("projects", projProjectService.findAllPublished("id", "name"));
    return mv;
  }

  @RequestMapping(value = { "sptAllProcessEditManage", "" })
  public ModelAndView sptAllProcessEditManage(HttpServletRequest req) {
    ModelAndView mv = this.getModelAndView();
    ProjProjectService projProjectService = ContextHolder
        .getSpringBean("projProjectService");
    mv.addObject("projects", projProjectService.findAllPublished("id", "name"));
    return mv;
  }

  @Override
	@RequestMapping("edit")
	public ModelAndView edit(String id, HttpServletRequest req)
			throws Exception {
		ModelAndView mv = new ModelAndView("sparepart/sparepart/plan/edit");

		String categoryId = req.getParameter("categoryId");
		String relationId=req.getParameter("sparepartId");
		
		String categoryName = "";
		SptSparepartPlan model = null;
		if (StringUtils.isEmpty(id)) {
			model = new SptSparepartPlan();
			model.setId(HibernateUUIDGenerator.generate());
			
			IUser u=ContextHolder.getLoginUser();
			
			model.setUseStaffId(u.getUsername());
			model.setUseStaffName(u.getFullname());
			
			if (StringUtils.isNotEmpty(categoryId)) {
				model.setSptSparepartCategoryId(categoryId);
				categoryName = this.sptSparepartCategoryService.findOne(
						categoryId).getName();
			}
			String providerId=req.getParameter("providerId");
      if(StringUtils.isNotBlank(providerId))
      {
        model.setManufacturerProviderId(providerId);
        model.setManufacturerProviderName(prdProviderService.findOne(providerId).getName());
      }
      model.setStockInDate(new Date());
        

		} else {
		  JqGridRequest request = new JqGridRequest();
		  request.addFilterRule("id", JqGridFilterRuleOp.eq, id);
		  if(StringUtils.isNotBlank(relationId))
		      request.addFilterRule("relation_id", JqGridFilterRuleOp.eq, relationId);
			model = this.getService().findOneByRequest(request);
			categoryName = this.sptSparepartCategoryService.findOne(
					model.getSptSparepartCategoryId()).getName();

		}
		
		
		String projectId=req.getParameter("projectId");
    if(StringUtils.isNotEmpty(projectId))
    {
      List<ProjProject> list=new ArrayList<ProjProject>();
      list.add(projProjectService.findOne(projectId));
      mv.addObject("projects",list
          );
    }else
    {
      mv.addObject("projects",
          projProjectService.findAllPublished("id", "name"));
    }
    String ty=req.getParameter("ty");
    if(StringUtils.isNotBlank(ty))
    {
      mv.addObject("ty", ty);
      String sourceId=req.getParameter("sourceId");
      mv.addObject("sourceId", sourceId);
      if(ty.equals("sparepartIn"))
      {
        model.setStatus("已入库");
      }
    }

		mv.addObject("categoryName", categoryName);

		mv.addObject("model", model);

		return mv;
	}

  @RequestMapping("save")
  @ResponseBody
  public ResultMessage save(SptSparepartPlan model, HttpServletRequest req) {

    String ty = req.getParameter("ty");
    Integer useStatus = 1;
    if (StringUtils.isNotBlank(ty) && ty.equals("sparepartIn")) {
      SptSparepartRelationService sptSparepartRelationService = ContextHolder
          .getSpringBean("sptSparepartRelationService");
      String sourceId = req.getParameter("sourceId");
      SptSparepartRelation sptRelation = new SptSparepartRelation();
      sptRelation.setSparepartId(sourceId);
      sptRelation.setCiId(model.getCode());
      sptRelation.setStatus(1);
      sptRelation.setTypeKey("sparepartIn");
      sptSparepartRelationService.saveOrUpdate(sptRelation);
      useStatus = 2;
    }
    if (StringUtils.isNotBlank(model.getProjectId())) {
      String projectName = projProjectService.findOne(model.getProjectId())
          .getName();
      model.setProjectName(projectName);

    }
    model.setUseStatus(useStatus);
    this.getService().saveOrUpdateAndSpecific(model, req);
    return ResultMessage.newInstance(true, null, model.getId());
  }

  @RequestMapping("search")
  public ModelAndView search(JqGridRequest request, HttpServletRequest req)
      throws Exception {
    ModelAndView mv = new ModelAndView("sparepart/sparepart/search");
    CusCustomerService cusCustomerService = ContextHolder
        .getSpringBean("cusCustomerService");
    mv.addObject("customerCiCounts", cusCustomerService.getCustomerCiCount());

    AppDictService appDictService = ContextHolder
        .getSpringBean("appDictService");
    mv.addObject("var_assetStatus", appDictService.findByType("CI_STATUS"));

    mv.addObject("customerId", cusCustomerService.getCompanyCustomer().getId());

    return mv;
  }

  @RequestMapping("viewEdit")
  public ModelAndView viewEdit(String id, HttpServletRequest req)
      throws Exception {
    ModelAndView mv = new ModelAndView("sparepart/sparepart/viewEdit");

    JqGridRequest request = new JqGridRequest();
    request.addFilterRule("id", JqGridFilterRuleOp.eq, id);
    List<Map<String, Object>> list = sptSparepartPlanService
        .findAllDetailByRequest(request).getContent();
    if (list != null && list.size() > 0) {
      mv.addObject("model", list.get(0));
    } else {
      mv.addObject("model", null);
    }

    return mv;
  }

  @RequestMapping("viewSptEdit")
  public String viewSptEdit(String id, HttpServletRequest req,
      RedirectAttributes redirectAttributes) throws Exception {

    JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
    String sql = "select * from v_spt_process where id='" + id + "'";
    List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
    String url = "";
    if (list.size() > 0) {
      String type = list.get(0).get("spt_type").toString();
      switch (type) {
      case "备件归还":
        url = "/sparepart/sparepartBack/view";
        break;
      case "备件报废":
        url = "/sparepart/sparepartDiscard/view";
        break;
      case "备件采购":
        url = "/sparepart/sparepartIn/view";
        break;
      case "备件领用":
        url = "/sparepart/sparepartOut/view";
        break;
      default:
      }

    }

    redirectAttributes.addAttribute("id", id);
    return "redirect:" + url;
  }

  @RequestMapping("inOutList")
  public ModelAndView inOutList(String sparepartId, HttpServletRequest req)
      throws Exception {
    ModelAndView mv = this.getModelAndView();

    mv.addObject("id", sparepartId);
    return mv;
  }

  @RequestMapping("projectUsed")
  @ResponseBody
  public PageResponse<Map<String, Object>> projectUsed(String sparepartId,
      JqGridRequest request, HttpServletRequest req) {
    return sptSparepartPlanService.findAllProjectUsedByRequest(sparepartId,
        request);
  }

  @RequestMapping("updateStore")
  @ResponseBody
  public ResultMessage updateStore(JqGridRequest request, HttpServletRequest req) {
    return sptSparepartPlanService.updateStore();
  }
  
  @RequestMapping("updateStatus")
  @ResponseBody
  public ResultMessage updateStatus(HttpServletRequest req) {
    String status=req.getParameter("status");
    String sptId=req.getParameter("sparepartId");
    this.getService().updateStatus(sptId, status);
    return ResultMessage.newInstance(true);
  }

  @Override
  @RequestMapping(value = { "manage", "" })
  public ModelAndView manage(HttpServletRequest req) {
    CusCustomerService cusCustomerService = ContextHolder
        .getSpringBean("cusCustomerService");
    ModelAndView mv = this.getModelAndView();
    mv.addObject("customerCiCounts", cusCustomerService.getCustomerCiCount());

    AppDictService appDictService = ContextHolder
        .getSpringBean("appDictService");
    mv.addObject("var_assetStatus", appDictService.findByType("CI_STATUS"));

    return mv;
  }

  @RequestMapping("autocompleteSpeclist")
  @ResponseBody
  public List<Map<String, Object>> autocompleteSpeclist(JqGridRequest request,
      HttpServletRequest req) {
    String categoryId = req.getParameter("categoryId");
    String term = req.getParameter("term");
    List<Map<String, Object>> result = null;
    ConfCiService confCiService = ContextHolder.getSpringBean("confCiService");
    request.addFilterRule("are_company", JqGridFilterRuleOp.eq, "1");
    if (StringUtils.isNotEmpty(term)) {
      request.isPageable(false);
      request.setRows(10);
      request.setSearchString("  specification LIKE '%" + term
          + "%' OR   model LIKE '%" + term.toUpperCase() + "%' ");
    }
    if (StringUtils.isNotEmpty(categoryId)) {
      request.addFilterRule("conf_category_id", JqGridFilterRuleOp.eq,
          categoryId);
    }
    result = confCiService.listSepAndModel(request);

    return result;

  }
  
  @RequestMapping("delete")
  @ResponseBody
  @Override
  public ResultMessage delete(String id, HttpServletRequest req) {
    String sptId=req.getParameter("sparepartId");
    SptSparepartPlan sp=this.get(id);
    SptSparepartRelationService sptSparepartRelationService = ContextHolder.getSpringBean("sptSparepartRelationService");
    sptSparepartRelationService.deleteByCiIdAndsptId(sp.getCode(), sptId);
    this.getService().delete(id);
    return ResultMessage.newInstance(true);
  }

}
